package com.stxx.stiot2.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.StrUtil;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.framwork.utils.StoreUtils;
import com.stxx.stiot2.domain.SysUser;
import com.stxx.stiot2.service.SysUserService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Fuzhenlei
 * @date 2025-05-23 15:24:32
 */
@Component
public class SysUserServiceImpl implements SysUserService{
    @Inject
    StoreUtils storeUtils;

    @Override
    public SysUser queryById(Integer id) {
        try {
            return storeUtils.selectById(id,SysUser.class);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insert(SysUser bean) throws SQLException {
        validEntityBeforeSave(bean);
        return storeUtils.insert(bean);
    }

    @Override
    public int update(SysUser bean) throws SQLException {
        validEntityBeforeSave(bean);
        return storeUtils.update(bean);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUser bean){
        if(StrUtil.isNotEmpty(bean.getPassword())){
            bean.setPassword(BCrypt.hashpw(bean.getPassword()));
        }

    }



    @Override
    public int delete(Integer name) throws SQLException {
        return storeUtils.delete(SysUser.class,name);
    }

    @Override
    public int deleteByIds(Integer[] ids) throws SQLException {
        return storeUtils.deleteByIds(SysUser.class, ids);
    }

    @Override
    public List<SysUser> list(SysUser obj) throws SQLException {
        return storeUtils.selectList(SysUser.class,obj);
    }

    @Override
    public PageResult<SysUser> pageList(SysUser obj, PageQuery pageQuery) throws SQLException {
        return storeUtils.selectPageList(SysUser.class,obj,pageQuery);
    }

    @Override
    public SysUser queryByUsername(String username) throws SQLException {
        return storeUtils.sql("select * from "+StoreUtils.getTableName("sys_user")+" where user_name = ?",username).queryRow(SysUser.class);
    }

    @Override
    public void resetPassord(Integer userId) throws SQLException {
        storeUtils.sql("update "+StoreUtils.getTableName("sys_user")+"set password = ? where user_id = ?", BCrypt.hashpw("123456"),userId).update();
    }
}
